import type {
	CommonResult,
	UserInfoResult,
	AvatarUploadResult,
} from '@/types'
import { http } from '@/utils/http'
import { getUserApiPrefix } from '@/utils/config'

/**
 * 获取用户信息
 */
export const getUserInfoAPI = () => {
	return http<UserInfoResult>({
		url: `${getUserApiPrefix()}/tocCustom/info`,
		method: 'GET',
	})
}

/**
 * 上传头像文件
 */
export const uploadAvatarAPI = (filePath: string) => {
	return new Promise<AvatarUploadResult>((resolve, reject) => {
		// 获取token
		const token = uni.getStorageSync('token');
		
		uni.uploadFile({
			url: `${getUserApiPrefix()}/sys-file/upload`,
			filePath: filePath,
			name: 'file',
			formData: {
				// 添加额外的表单数据，有助于后端处理
				'type': 'avatar'
			},
			header: {
				'Authorization': token ? `Bearer ${token}` : '',
				'Content-Type': 'multipart/form-data'
			},
			success: (res: any) => {
				console.log('上传响应:', res);
				try {
					if (res.statusCode >= 200 && res.statusCode < 300) {
						const data = JSON.parse(res.data);
						if (data.code === 0 || data.success) {
							// 根据实际后端响应结构调整
							resolve(data.data || data.result);
						} else {
							uni.showToast({
								icon: 'none',
								title: data.msg || data.message || '上传失败'
							});
							reject(data);
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: `上传失败，状态码: ${res.statusCode}`
						});
						reject(new Error(`HTTP ${res.statusCode}`));
					}
				} catch (error) {
					console.error('解析上传响应失败:', error, res.data);
					uni.showToast({
						icon: 'none',
						title: '上传响应解析失败'
					});
					reject(error);
				}
			},
			fail: (err: any) => {
				console.error('上传失败:', err);
				uni.showToast({
					icon: 'none',
					title: '上传失败，请重试'
				});
				reject(err);
			}
		});
	});
};

/**
 * 更新用户头像URL
 */
export const updateAvatarAPI = (avatar: string) => {
	return http<CommonResult>({
		url: `${getUserApiPrefix()}/tocCustom/avatar`,
		method: 'PUT',
		data: {
			avatar
		}
	})
}

/**
 * 更新用户信息
 */
export const updateUserInfoAPI = (userInfo: UserInfoResult) => {
	return http<CommonResult>({
		url: `${getUserApiPrefix()}/tocCustom/info`,
		method: 'PUT',
		data: userInfo
	})
}
